package com.example.contentclient;

import android.annotation.SuppressLint;
import android.content.ContentUris;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public class MoniterSmsActivity extends AppCompatActivity implements View.OnClickListener {

    private SmsGetObserver mObserver;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_monitersms);
        findViewById(R.id.btn_send).setOnClickListener(this);
        Uri uri=Uri.parse("content://sms");
        mObserver = new SmsGetObserver(this);
        getContentResolver().registerContentObserver(uri,true,mObserver);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //取消注册监听器
        getContentResolver().unregisterContentObserver(mObserver);
    }

    private static class SmsGetObserver extends ContentObserver
    {
        private final Context mContext;
        public SmsGetObserver(Context context)
        {
            //Looper为每个线程都有的一个轮询器，这里将主线程的轮询器传了进去。
            super(new Handler(Looper.getMainLooper()));
            this.mContext=context;
        }
        @SuppressLint("Range")
        @Override
        public void onChange(boolean selfChange, @Nullable Uri uri) {
            super.onChange(selfChange, uri);
            if(uri==null)
            {
                return;
            }
            if(uri.toString().contains("content://sms/raw")||
                  uri.toString().equals("content://sms"))
            {
                return;
            }
            //通过内容解析器获取符合条件的结果游标(根据日期降序排序)
            Cursor cursor = mContext.getContentResolver().query(uri, new String[]{"address", "body", "date"}, null, null, "date DESC");
            if(cursor.moveToNext())
            {
                //短信的发送号码
                String sender = cursor.getString(cursor.getColumnIndex("address"));
                //短信内容
                String body = cursor.getString(cursor.getColumnIndex("body"));
                Log.d("tang",String.format("sender:%s,content:%s",sender,body));
            }
            cursor.close();
        }
    }
    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case R.id.btn_sms:

                break;
        }

    }
}
